from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, ForeignKey, Enum, BigInteger
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from enum import Enum as PyEnum
from ..core.database import Base

class FileType(PyEnum):
    FILE = "file"
    FOLDER = "folder"

class File(Base):
    __tablename__ = "files"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), nullable=False)
    file_type = Column(Enum(FileType), nullable=False)
    path = Column(String(500), nullable=False)  # 文件系统路径
    size = Column(BigInteger, default=0)  # 文件大小（字节）
    mime_type = Column(String(100), nullable=True)
    parent_id = Column(Integer, ForeignKey("files.id"), nullable=True)
    owner_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    department_id = Column(Integer, ForeignKey("departments.id"), nullable=True)
    level = Column(Integer, default=0)  # 文件夹层级，0为根目录
    share_level = Column(String(20), default="private")  # 共享级别
    description = Column(Text, default="")  # 文件描述
    tags = Column(Text, default="")  # 文件标签，用逗号分隔
    is_deleted = Column(Boolean, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    owner = relationship("User", back_populates="files")
    department = relationship("Department", back_populates="files")
    parent = relationship("File", remote_side=[id], backref="children")
    permissions = relationship("FilePermission", back_populates="file")
    shares = relationship("FileShare", back_populates="file")
    versions = relationship("FileVersion", back_populates="file", order_by="FileVersion.version_number.desc()")